// 将后端返回的 pathPermsList 转换为路由配置
// 仅支持 permType === 'MENU' 且存在有效 path 的项
// path 形如 '@/views/nested/org/index'

import Layout from '@/layout'

function normalizeViewPath(rawPath) {
  if (!rawPath || typeof rawPath !== 'string') return null
  // '@/views/xxx' -> 'views/xxx'
  const path = rawPath.replace(/^@\//, '')
  if (!path.startsWith('views/')) return null
  return path
}

function buildRouteFromPerm(perm) {
  const viewPath = normalizeViewPath(perm.path)
  if (!viewPath) return null

  // 以 views/ 开头，提取子路径作为路由 path
  const withoutViews = viewPath.replace(/^views\//, '')
  // e.g. nested/org/index => [nested, org, index]
  const segments = withoutViews.split('/')
  if (segments.length === 0) return null

  // 页面组件懒加载
  const component = () => import(`@/${viewPath}`)

  // 将 title 使用 permName；name 使用最后一段首字母大写
  const last = segments[segments.length - 1]
  const name = (last || 'Page').replace(/(^|[-_])(\w)/g, (_, __, c) => c ? c.toUpperCase() : '')
  const meta = { title: perm.permName || name }

  // 生成分层路由：前面段作为父级，最后一段为叶子
  if (segments.length === 1) {
    return {
      path: `/${segments[0]}`,
      name,
      component,
      meta
    }
  }

  // 形如 nested/xxx/index -> 归到 /nested 下
  const childPath = segments.slice(1).join('/').replace(/\/index$/, '')
  return {
    path: `/${segments[0]}`,
    component: Layout,
    redirect: `/${segments[0]}/${segments[1]}`,
    name: segments[0].replace(/(^|[-_])(\w)/g, (_, __, c) => c ? c.toUpperCase() : ''),
    meta: { title: segments[0] === 'nested' ? '内容管理' : perm.permName || name, icon: segments[0] === 'nested' ? 'nested' : 'form' },
    children: [
      {
        path: childPath,
        name,
        component,
        meta
      }
    ]
  }
}

export function buildRoutesFromPerms(pathPermsList) {
  if (!Array.isArray(pathPermsList)) return []
  const menus = pathPermsList.filter(item => item && item.permType === 'MENU' && item.path)
  const built = menus.map(buildRouteFromPerm).filter(Boolean)

  // 合并同一一级 path 的 children（如多个 nested/*）
  const map = new Map()
  for (const r of built) {
    if (r.children && r.component === Layout) {
      const key = r.path
      if (map.has(key)) {
        const exist = map.get(key)
        // 合并 children，去重按 path
        const existedPaths = new Set(exist.children.map(c => c.path))
        for (const c of r.children) {
          if (!existedPaths.has(c.path)) exist.children.push(c)
        }
      } else {
        map.set(key, { ...r, children: [...r.children] })
      }
    } else {
      // 非分组的直接按唯一 key 存
      const key = r.path
      if (!map.has(key)) map.set(key, r)
    }
  }

  return Array.from(map.values())
}

